package com.zqxx.examine.portal.controller.page;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zqxx.examine.common.utils.QuestionAdapter;
import com.zqxx.examine.model.exam.UserQuestionHistory;
import com.zqxx.examine.model.practice.KnowledgePointAnalysisResult;
import com.zqxx.examine.model.practice.TypeAnalysis;
import com.zqxx.examine.model.question.Field;
import com.zqxx.examine.model.question.KnowledgePoint;
import com.zqxx.examine.model.question.QuestionQueryResult;
import com.zqxx.examine.model.question.QuestionStatistic;
import com.zqxx.examine.model.question.QuestionType;
import com.zqxx.examine.portal.security.UserInfo;
import com.zqxx.examine.portal.service.QuestionHistoryService;
import com.zqxx.examine.portal.service.QuestionService;

@Controller
public class PracticePage
{
  @Autowired
  private QuestionService questionService;
  @Autowired
  private QuestionHistoryService questionHistoryService;
  
  @RequestMapping(value={"/student/practice-improve/{fieldId}/{knowledgePointId}/{questionTypeId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String practiceImprove(Model model, HttpServletRequest request, @PathVariable("fieldId") int fieldId, @PathVariable("knowledgePointId") int knowledgePointId, @PathVariable("questionTypeId") int questionTypeId)
  {
    String strUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + "/";
    
    List<QuestionQueryResult> qqrList = this.questionService.getQuestionAnalysisListByPointIdAndTypeId(questionTypeId, knowledgePointId);
    
    String questionTypeName = "";
    String fieldName = "";
    try
    {
      fieldName = ((QuestionQueryResult)qqrList.get(0)).getPointName().split(">")[1];
    }
    catch (Exception localException) {}
    Map<Integer, QuestionType> questionTypeMap = this.questionService.getQuestionTypeMap();
    for (Map.Entry<Integer, QuestionType> entry : questionTypeMap.entrySet()) {
      if (((Integer)entry.getKey()).intValue() == questionTypeId)
      {
        questionTypeName = ((QuestionType)entry.getValue()).getName();
        break;
      }
    }
    int amount = qqrList.size();
    StringBuilder sb = new StringBuilder();
    for (QuestionQueryResult qqr : qqrList)
    {
      QuestionAdapter adapter = new QuestionAdapter(qqr, strUrl);
      sb.append(adapter.getStringFromXML());
    }
    model.addAttribute("questionStr", sb.toString());
    model.addAttribute("amount", Integer.valueOf(amount));
    model.addAttribute("fieldName", fieldName);
    model.addAttribute("questionTypeName", questionTypeName);
    model.addAttribute("practiceName", "强化练习");
    model.addAttribute("knowledgePointId", Integer.valueOf(knowledgePointId));
    model.addAttribute("questionTypeId", Integer.valueOf(questionTypeId));
    model.addAttribute("fieldId", Integer.valueOf(fieldId));
    return "practice-improve-qh";
  }
  
  @RequestMapping(value={"/student/practice-incorrect/{fieldId}/{knowledgePointId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String practiceIncorrectQuestions(Model model, HttpServletRequest request, @PathVariable("fieldId") int fieldId, @PathVariable("knowledgePointId") int knowledgePointId)
  {
    String strUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + "/";
    

    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    
    Map<Integer, List<UserQuestionHistory>> historyMap = this.questionHistoryService.getUserQuestionHist(userInfo.getUserid(), fieldId);
    
    List<UserQuestionHistory> historyList = (List)historyMap.get(Integer.valueOf(knowledgePointId));
    
    List<Integer> idList = new ArrayList();
    for (UserQuestionHistory history : historyList) {
      if (!history.isRight()) {
        idList.add(Integer.valueOf(history.getQuestionId()));
      }
    }
    List<QuestionQueryResult> qqrList = new ArrayList<QuestionQueryResult>();
    if (idList.size() > 0) {
      qqrList = this.questionService.getQuestionAnalysisListByIdList(idList);
    }
    int amount = idList.size();
    StringBuilder sb = new StringBuilder();
    for (QuestionQueryResult qqr : qqrList)
    {
      QuestionAdapter adapter = new QuestionAdapter(qqr, strUrl);
      sb.append(adapter.getStringFromXML());
    }
    model.addAttribute("questionStr", sb.toString());
    model.addAttribute("amount", Integer.valueOf(amount));
    model.addAttribute("questionTypeName", "错题库");
    model.addAttribute("practiceName", "错题练习");
    return "practice-improve";
  }
  
  @RequestMapping(value={"/student/practice-improve-his/{fieldId}/{knowledgePointId}/{questionTypeId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  @ResponseBody
  public List<Integer> getFinishedQuestionId(Model model, HttpServletRequest request, @PathVariable("fieldId") int fieldId, @PathVariable("knowledgePointId") int knowledgePointId, @PathVariable("questionTypeId") int questionTypeId)
  {
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    Map<Integer, List<UserQuestionHistory>> historyMap = this.questionHistoryService.getUserQuestionHist(userInfo.getUserid(), fieldId);
    
    List<Integer> l = new ArrayList();
    

    return l;
  }
  
  @RequestMapping(value={"/student/practice-test/{fieldId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String practiceStartNew(Model model, HttpServletRequest request, @PathVariable("fieldId") int fieldId)
  {
    String strUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + "/";
    
    Map<Integer, Map<Integer, List<QuestionQueryResult>>> map = this.questionService.getQuestionMapByFieldId(fieldId, null);
    List<QuestionQueryResult> qqrList = new ArrayList();
    for (Map.Entry<Integer, Map<Integer, List<QuestionQueryResult>>> entry : map.entrySet())
    {
      if (((Map)entry.getValue()).containsKey(Integer.valueOf(1))) {
        qqrList.addAll((Collection)((Map)entry.getValue()).get(Integer.valueOf(1)));
      }
      if (((Map)entry.getValue()).containsKey(Integer.valueOf(2))) {
        qqrList.addAll((Collection)((Map)entry.getValue()).get(Integer.valueOf(2)));
      }
      if (((Map)entry.getValue()).containsKey(Integer.valueOf(3))) {
        qqrList.addAll((Collection)((Map)entry.getValue()).get(Integer.valueOf(3)));
      }
    }
    int amount = 0;
    if (qqrList.size() == 0)
    {
      model.addAttribute("errorMsg", "无可用的题目");
      return "error";
    }
    StringBuilder sb = new StringBuilder();
    Random random = new Random();
    for (int i = 0; i < 20; i++)
    {
      int questionCount = qqrList.size();
      int index = random.nextInt(questionCount);
      QuestionAdapter adapter = new QuestionAdapter((QuestionQueryResult)qqrList.get(index), strUrl);
      sb.append(adapter.getStringFromXML());
      qqrList.remove(index);
      amount++;
      if (qqrList.size() == 0) {
        break;
      }
    }
    model.addAttribute("questionStr", sb.toString());
    model.addAttribute("amount", Integer.valueOf(amount));
    model.addAttribute("questionTypeName", "随机题");
    model.addAttribute("practiceName", "随机练习");
    return "practice-improve";
  }
  
  @RequestMapping(value={"/student/practice-list"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String practiceListPage(Model model, HttpServletRequest request, @RequestParam(value="fieldId", required=false, defaultValue="0") int fieldId)
  {
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    List<Field> fieldList = this.questionService.getAllField(null);
    if (fieldId == 0) {
      fieldId = ((Field)fieldList.get(0)).getFieldId();
    }
    Map<Integer, Map<Integer, QuestionStatistic>> questionMap = this.questionService.getTypeQuestionStaticByFieldId(fieldId);
    Map<Integer, Map<Integer, QuestionStatistic>> historyMap = this.questionHistoryService.getTypeQuestionHistStaticByFieldId(fieldId, userInfo.getUserid());
    Map<Integer, QuestionStatistic> historyStatisticMap = this.questionHistoryService.getQuestionHistStaticByFieldId(fieldId, userInfo.getUserid());
    Map<Integer, KnowledgePoint> pointMap = this.questionService.getKnowledgePointByFieldId(null, new int[] { fieldId });
    
    List<KnowledgePointAnalysisResult> kparl = new ArrayList();
    for (Map.Entry<Integer, Map<Integer, QuestionStatistic>> entry : questionMap.entrySet())
    {
      KnowledgePointAnalysisResult kpar = new KnowledgePointAnalysisResult();
      kpar.setKnowledgePointId(((Integer)entry.getKey()).intValue());
      List<TypeAnalysis> tal = new ArrayList();
      int totalRightAmount = 0;
      int totalAmount = 0;
      for (Map.Entry<Integer, QuestionStatistic> entry1 : entry.getValue().entrySet())
      {
        TypeAnalysis ta = new TypeAnalysis();
        ta.setQuestionTypeId(((Integer)entry1.getKey()).intValue());
        ta.setQuestionTypeName(((QuestionStatistic)entry1.getValue()).getQuestionTypeName());
        int rightAmount = 0;
        int wrongAmount = 0;
        try
        {
          rightAmount = ((QuestionStatistic)((Map)historyMap.get(entry.getKey())).get(entry1.getKey())).getRightAmount();
        }
        catch (Exception localException) {}
        try
        {
          wrongAmount = ((QuestionStatistic)((Map)historyMap.get(entry.getKey())).get(entry1.getKey())).getWrongAmount();
        }
        catch (Exception localException1) {}
        ta.setRightAmount(rightAmount);
        ta.setWrongAmount(wrongAmount);
        ta.setRestAmount(((QuestionStatistic)entry1.getValue()).getAmount() - rightAmount - wrongAmount);
        tal.add(ta);
        if (kpar.getKnowledgePointName() == null) {
          kpar.setKnowledgePointName(((QuestionStatistic)entry1.getValue()).getPointName());
        }
        totalRightAmount += rightAmount;
        totalAmount += ((QuestionStatistic)entry1.getValue()).getAmount();
      }
      kpar.setTypeAnalysis(tal);
      if (totalAmount > 0) {
        kpar.setFinishRate(totalRightAmount / totalAmount);
      }
      kparl.add(kpar);
    }
    model.addAttribute("kparl", kparl);
    model.addAttribute("fieldId", Integer.valueOf(fieldId));
    model.addAttribute("historyMap", historyStatisticMap);
    model.addAttribute("pointMap", pointMap);
    model.addAttribute("fieldList", fieldList);
    return "practice";
  }
}
